//
//  FBBaseHTTPRequestModel.m
//  FindBook
//
//  Created by zhaoxu_liu on 13-11-1.
//  Copyright (c) 2013年 lzx. All rights reserved.
//

#import "FBBaseHTTPRequestModel.h"

@implementation FBBaseHTTPRequestModel

- (BOOL)handleResponseString:(id)aResponseString
{
    id jsonValue = [aResponseString JSONValue];
    if (nil == jsonValue)
    {
        self.error = [NSError errorWithDomain:FBErrorDomain
                                         code:FBErrorCode_ServerData
                                     userInfo:[NSDictionary dictionaryWithObject:FBErrorString_ServerData forKey:NSLocalizedDescriptionKey]];
        return NO;
    }
    
    BOOL ret = NO;
    
    if ([jsonValue isKindOfClass:[NSDictionary class]])
    {
        FBHTTPModelRspData* rspData = [[FBHTTPModelRspData alloc] init];
        NSInteger resultcode = [[jsonValue valueForKey:@"resultcode"] integerValue];
        rspData.resultcode = resultcode;
        rspData.reason = [jsonValue valueForKey:@"reason"];
        id result = [jsonValue valueForKey:@"result"];
        rspData.result = result;
        self.responseObject = rspData;
        
        if (200 == resultcode)
        {
            if (result || ([result isKindOfClass:[NSString class]] && [result length] > 0))
            {
                ret = [self handleResponseJSON:result];
            }
            else
            {
                ret = YES;
            }
        }
        else
        {
            // status为非200时，如果 handleModelWillFail:返回NO，按照"成功"处理
            ret = [self handleModelWillFail];
            if (ret)
            {
                self.error = [NSError errorWithDomain:FBErrorDomain code:resultcode userInfo:[NSDictionary dictionaryWithObject:rspData.reason forKey:NSLocalizedDescriptionKey]];
                ret = NO;
            }
            else
            {
                if (result || ([result isKindOfClass:[NSString class]] && [result length] > 0))
                {
                    [self handleResponseJSON:result];
                }
                ret = YES;
            }
        }

    }
    else
    {
        self.error = [NSError errorWithDomain:FBErrorDomain
                                         code:FBErrorCode_ServerData
                                     userInfo:[NSDictionary dictionaryWithObject:FBErrorString_ServerData forKey:NSLocalizedDescriptionKey]];
        ret = NO;
    }
    return ret;
}

- (BOOL)handleModelWillFail
{
    return YES;
}

- (BOOL)handleResponseJSON:(id)aJSON
{
    return YES;
}

- (FBHTTPModelRspData *)ewRspData
{
    if ([self.responseObject isKindOfClass:[FBHTTPModelRspData class]])
    {
        return (FBHTTPModelRspData *)self.responseObject;
    }
    return nil;
}

@end

@implementation FBHTTPModelRspData


@end
